//
//  MNDPlusRecordContainerViewController.m
//  PlusTenderDemo
//
//  Created by Vitas on 2018/7/18.
//  Copyright © 2018年 Bylongma. All rights reserved.
//

#import "MNDPlusRecordContainerViewController.h"
#import "MNDPlusRecordViewController.h"
#import "UIView+JKFrame.h"
#import "MNDPlusMoneyStatisticsModel.h"
#import "MNDPlusRecordDetailViewController.h"

typedef enum : NSUInteger {
    kTopTypeHold = 100,//持有中
    kTopTypeExit//已退出
} kTopType;

@interface MNDPlusRecordContainerViewController ()<UIScrollViewDelegate,MNDPlusRecordListDelegate>


@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@property (weak, nonatomic) IBOutlet UIView *segementView;
@property (weak, nonatomic) IBOutlet UIButton *holdButton;
@property (weak, nonatomic) IBOutlet UIButton *exitButton;
@property(nonatomic, assign) CGRect originRect;
/*! 头部view */
@property (weak, nonatomic) IBOutlet UIView *headerView;
/*! 头部背景图 */
@property (weak, nonatomic) IBOutlet UIImageView *headerImageView;
/*! 待收本金title */
@property (weak, nonatomic) IBOutlet UILabel *waitTotalMoneyTitleLabel;
/*! 待收本金 */
@property (weak, nonatomic) IBOutlet UILabel *waitTotalMoneyLabel;
/*! 待收收益title */
@property (weak, nonatomic) IBOutlet UILabel *waitEarningsTitleLabel;
/*! 待收收益 */
@property (weak, nonatomic) IBOutlet UILabel *waitEarningsLabel;
/*! 已收收益title */
@property (weak, nonatomic) IBOutlet UILabel *currentEarningsTitleLabel;
/*! 已收收益 */
@property (weak, nonatomic) IBOutlet UILabel *currentEarningsLabel;
/*! 头部高度 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *headrViewHeight;
//头部最大高度
@property (nonatomic) CGFloat headerMaxHeight;
//头部最小高度
@property (nonatomic) CGFloat headerMinHeight;


@end

@implementation MNDPlusRecordContainerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self loadData];
    [self setupUI];
    
    [self showInvestDetail];
    if (self.shouldCustomBack) {
        [self customBackBarButton];
    }
    // Do any additional setup after loading the view.
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.originRect = self.segementView.frame;
    
}

- (void)customBackBarButton {
    UIImage *backImage = [UIImage imageNamed:@"navi_back_btn_black"];
    
    //创建返回按钮
    UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:backImage
                                                                          style:UIBarButtonItemStylePlain
                                                                         target:self
                                                                         action:@selector(backAction:)];
    //设置返回按钮的颜色
    [backBarButtonItem setTintColor:kColorBackButtonColor];
    
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    //将两个BarButtonItem都返回给NavigationItem
    if (@available(iOS 11.0, *)) {
        self.navigationItem.leftBarButtonItem = backBarButtonItem;
    } else {
        self.navigationItem.leftBarButtonItems = @[spaceItem, backBarButtonItem];
    }
    
}

- (void)backAction:(id)sender {
    [self.tabBarController setSelectedIndex:3];
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)showInvestDetail {
    if (self.sign_id != nil) {
        MNDPlusRecordDetailViewController *investmentDetailVC = [UIStoryboard  viewControllerWithIdentifier:@"MNDPlusRecordDetailViewController"];
        investmentDetailVC.shouldCustomBack = self.shouldCustomBack;
        investmentDetailVC.sign_id = self.sign_id;
        investmentDetailVC.title = self.plusTitle;
        [self.navigationController pushViewController:investmentDetailVC animated:YES];
    }
}

#pragma mark - 搭建界面
- (void)setupUI {
    
    self.naviBarTranslucent = YES;
    self.leftBarTintColor = [UIColor whiteColor];
    self.barTitleColor = [UIColor whiteColor];
    
    //头部的高度根据背景图确定
    UIImage *headerImage = [UIImage imageNamed:@"investment_racord_header_big"];
    //    NSLog(@"height: %f", kScreenHeight);
    if (kScreenHeight >= 812) { //iPhone X
        self.headrViewHeight.constant = headerImage.size.height + 40;
    } else {
        self.headrViewHeight.constant = headerImage.size.height;
    }
    
    self.headerMaxHeight = self.headrViewHeight.constant;
    
    UIImage *headerSmallImage = [UIImage imageNamed:@"investment_racord_header_small"];
    self.headerMinHeight = headerSmallImage.size.height;
    [self makeHeaderContentsInitialConstraints];
}
#pragma mark - 加载数据
- (void)loadData {
    
    kdeclare_weakself;
    [APIManager sendRequestWithURL:API_AUTO_PLUS_MONEY_STATISTICS parameters:[MNDSign signedParam] method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            MNDPlusMoneyStatisticsModel *model = [MNDPlusMoneyStatisticsModel mj_objectWithKeyValues:responseModel.data];
            [weakSelf configHeaderContents:model];
        }else {
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}



- (void)configHeaderContents:(MNDPlusMoneyStatisticsModel *)model {
    self.waitTotalMoneyLabel.text = model.tender_principal;
    self.waitEarningsLabel.text = model.interest_amount;
    self.currentEarningsLabel.text = model.accrued_interest_amount;
    
}

//pagecontroller与segementButton进行交互
- (IBAction)exchangePlusTypeAction:(UIButton *)sender {
    
    if (sender.tag == kTopTypeHold) {
        [self.scrollView scrollToLeft];
        self.holdButton.selected = YES;
        self.exitButton.selected = NO;
        
        [UIView animateWithDuration:0.25 animations:^{
            self.segementView.frame = CGRectMake(0, self.originRect.origin.y, self.segementView.bounds.size.width, self.segementView.bounds.size.height);
        }];
    }else {
        [self.scrollView scrollToRight];
        self.holdButton.selected = NO;
        self.exitButton.selected = YES;
        
        [UIView animateWithDuration:0.25 animations:^{
            self.segementView.frame = CGRectMake(kScreenWidth*0.5, self.originRect.origin.y, self.segementView.bounds.size.width, self.segementView.bounds.size.height);
        }];
    }
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"holdRecordVC"]) {//持有中记录
        MNDPlusRecordViewController *recordVC = [segue destinationViewController];
        recordVC.isExit = NO;
        recordVC.delegate = self;
    }else {//已退出记录
        MNDPlusRecordViewController *recordVC = [segue destinationViewController];
        recordVC.isExit = YES;
        recordVC.delegate = self;
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    if (scrollView.contentOffset.x > kScreenWidth*0.5) {//已退出记录
        self.holdButton.selected = NO;
        self.exitButton.selected = YES;
        
        [UIView animateWithDuration:0.25 animations:^{
            self.segementView.frame = CGRectMake(kScreenWidth*0.5, self.originRect.origin.y, self.segementView.bounds.size.width, self.segementView.bounds.size.height);
        }];
    }else {//已退出记录
        self.holdButton.selected = YES;
        self.exitButton.selected = NO;
        [UIView animateWithDuration:0.25 animations:^{
            self.segementView.frame = CGRectMake(0, self.originRect.origin.y, self.segementView.bounds.size.width, self.segementView.bounds.size.height);
        }];
    }
    NSLog(@"contentOffset.x = %lf",scrollView.contentOffset.x);
}

#pragma mark - MNDPlusRecordListDelegate
- (void)plusRecordListScroll:(UIScrollView *)scrollView withTotalNum:(NSInteger)totalNum{
    CGFloat offsetY = scrollView.contentOffset.y;
    NSLog(@"offsetY = %lf",offsetY);
    if (offsetY > 0 && totalNum > 2) {
        if (self.headrViewHeight.constant > self.headerMinHeight) {
            self.headerImageView.image = [UIImage imageNamed:@"investment_racord_header_small"];
            self.headrViewHeight.constant -= offsetY;
            [scrollView setContentOffset:CGPointMake(scrollView.contentOffset.x, 0)];
            
            if (self.waitEarningsTitleLabel.jk_top - self.waitTotalMoneyLabel.jk_bottom <= 2) {
                [self remakeHeaderContentsInitialConstraints];
            }
        }else {
            self.headrViewHeight.constant = self.headerMinHeight;
        }
        
    }
   
    
    if (offsetY < 0 && totalNum > 2) {
        
        if (self.headrViewHeight.constant < self.headerMaxHeight) {
            self.headerImageView.image = [UIImage imageNamed:@"investment_racord_header_big"];
            self.headrViewHeight.constant -= offsetY;
            [scrollView setContentOffset:CGPointMake(scrollView.contentOffset.x, 0)];
            
            CGFloat height = 20;
            if (kScreenHeight >= 812) {
                height = 60;
            }
            if (self.waitEarningsTitleLabel.jk_top > self.headerView.jk_centerY + height) {
                [self makeHeaderContentsInitialConstraints];
            }
        }else{
            self.headrViewHeight.constant = self.headerMaxHeight;
        }
    }
}

#pragma mark -- 头部约束
//设置头部内容的初始位置
- (void)makeHeaderContentsInitialConstraints {
    self.waitTotalMoneyLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:36];
    CGFloat edgeMargin = 16.0;
    WeakSelf(self);
    [self.waitTotalMoneyLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(weakself.headerView).offset(edgeMargin);
        make.centerY.equalTo(weakself.headerView);
    }];
    
    [self.waitTotalMoneyTitleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(weakself.waitTotalMoneyLabel.mas_top);
        make.leading.equalTo(weakself.waitTotalMoneyLabel);
    }];
    
    [self.waitEarningsLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(weakself.headerView).offset(edgeMargin);
        make.bottom.equalTo(weakself.headerView.mas_bottom).offset(-25.0);
    }];
    [self.waitEarningsTitleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(weakself.waitEarningsLabel.mas_top);
        make.leading.equalTo(weakself.waitEarningsLabel);
    }];
    
    [self.currentEarningsTitleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(weakself.headerView).offset(30.0);
        make.centerY.equalTo(weakself.waitEarningsTitleLabel);
    }];
    
    [self.currentEarningsLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(weakself.currentEarningsTitleLabel);
        make.centerY.equalTo(weakself.waitEarningsLabel);
    }];
}
//设置头部内容位置
- (void)remakeHeaderContentsInitialConstraints {
    self.waitTotalMoneyLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:19];
    CGFloat edgeMargin = 16.0;
    WeakSelf(self);
    [self.waitTotalMoneyLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(weakself.headerView).offset(edgeMargin);
        make.bottom.equalTo(weakself.headerView).offset(-10);
    }];
    
    [self.waitTotalMoneyTitleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(weakself.waitTotalMoneyLabel.mas_top);
        make.leading.equalTo(weakself.waitTotalMoneyLabel);
    }];
    
    [self.waitEarningsTitleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(weakself.headerView);
        make.centerY.equalTo(weakself.waitTotalMoneyTitleLabel);
    }];
    [self.waitEarningsLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(weakself.waitEarningsTitleLabel);
        make.centerY.equalTo(weakself.waitTotalMoneyLabel);
    }];
    
    NSDictionary *titleAtrrs = @{NSFontAttributeName : [UIFont fontWithName:@"PingFangSC-Regular" size:12]};
    CGSize titleSize = [weakself.currentEarningsTitleLabel.text sizeWithAttributes:titleAtrrs];
    
    NSDictionary *attrs = @{NSFontAttributeName : [UIFont fontWithName:@"PingFangSC-Regular" size:19]};
    CGSize size = [weakself.currentEarningsLabel.text sizeWithAttributes:attrs];
    
    [self.currentEarningsTitleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.equalTo(weakself.waitEarningsTitleLabel);
        
        //如果title的宽度大于金额的宽度，以title右边距为准
        if (titleSize.width >= size.width) {
            make.trailing.equalTo(weakself.headerView).offset(-edgeMargin);
        } else {
            make.leading.equalTo(weakself.currentEarningsLabel);
        }
    }];
    
    [self.currentEarningsLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.equalTo(weakself.waitEarningsLabel);
        if (titleSize.width > size.width) {
            make.leading.equalTo(weakself.currentEarningsTitleLabel);
        } else {
            make.trailing.equalTo(weakself.headerView).offset(-edgeMargin);
        }
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/



@end
